import { Graph } from '@antv/x6'
import { Stencil } from '@antv/x6-plugin-stencil'
import { Transform } from '@antv/x6-plugin-transform'
import { Selection } from '@antv/x6-plugin-selection'
import { Snapline } from '@antv/x6-plugin-snapline'
import { Keyboard } from '@antv/x6-plugin-keyboard'
import { Clipboard } from '@antv/x6-plugin-clipboard'
import { History } from '@antv/x6-plugin-history'
import { graphConfig, stencilConfig } from '../config/graph'
import { nodeConfigs, imageShapes } from '../config/nodes'

export function useGraph() {
  let graph: Graph
  let stencil: Stencil

  const initGraph = () => {
    graph = new Graph({
      container: document.getElementById('graph-container')!,
      ...graphConfig,
    })

    // Use plugins
    graph
      .use(
        new Transform({
          resizing: true,
          rotating: true,
        }),
      )
      .use(
        new Selection({
          rubberband: true,
          showNodeSelectionBox: true,
        }),
      )
      .use(new Snapline())
      .use(new Keyboard())
      .use(new Clipboard())
      .use(new History())

    return graph
  }

  const registerNodes = () => {
    Object.entries(nodeConfigs).forEach(([name, config]) => {
      Graph.registerNode(name, config as any, true)
    })
  }

  const initStencil = (graph: Graph) => {
    stencil = new Stencil({
      ...stencilConfig,
      target: graph,
    })

    document.getElementById('stencil')!.appendChild(stencil.container)

    // Basic flow chart nodes
    const r1 = graph.createNode({
      shape: 'custom-rect',
      label: '开始',
      attrs: {
        body: {
          rx: 20,
          ry: 26,
        },
      },
    })
    const r2 = graph.createNode({
      shape: 'custom-rect',
      label: '过程',
    })
    const r3 = graph.createNode({
      shape: 'custom-rect',
      attrs: {
        body: {
          rx: 6,
          ry: 6,
        },
      },
      label: '可选过程',
    })
    const r4 = graph.createNode({
      shape: 'custom-polygon',
      attrs: {
        body: {
          refPoints: '0,10 10,0 20,10 10,20',
        },
      },
      label: '决策',
    })
    const r5 = graph.createNode({
      shape: 'custom-polygon',
      attrs: {
        body: {
          refPoints: '10,0 40,0 30,20 0,20',
        },
      },
      label: '数据',
    })
    const r6 = graph.createNode({
      shape: 'custom-circle',
      label: '连接',
    })
    stencil.load([r1, r2, r3, r4, r5, r6], 'group1')

    // System design nodes
    const imageNodes = imageShapes.map((item) =>
      graph.createNode({
        shape: 'custom-image',
        label: item.label,
        attrs: {
          image: {
            'xlink:href': item.image,
          },
        },
      }),
    )
    stencil.load(imageNodes, 'group2')

    return stencil
  }

  return {
    initGraph,
    registerNodes,
    initStencil,
  }
} 